package com.sumer.brain.sys.service.impl;

import com.sumer.brain.common.config.JwtProperties;
import com.sumer.brain.common.model.SecurityUser;
import com.sumer.brain.common.utils.JwtUtil;
import com.sumer.brain.sys.model.req.LoginUserInfoReq;
import com.sumer.brain.sys.model.req.WechatLoginReq;
import com.sumer.brain.sys.service.LoginService;
import com.sumer.brain.sys.service.SysUserService;
import com.sumer.brain.sys.model.entity.SysUser;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@RequiredArgsConstructor
@Service
public class LoginServiceImpl implements LoginService {

    private final AuthenticationManager authenticationManager;

    private final JwtProperties jwtProperties;
    
    private final SysUserService sysUserService;

    @Override
    public String login(LoginUserInfoReq user) {

        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(user.getUsername(), user.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (authenticate != null && authenticate.isAuthenticated()) {
            Map<String, Object> map = new HashMap<>();
            SecurityUser securityUser = (SecurityUser) authenticate.getPrincipal();
            map.put("name", securityUser.getUsername());
            return JwtUtil.createJwt(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), String.valueOf(securityUser.getId()), map);
        }
        throw new RuntimeException("用户名或密码错误");
    }
    
    @Override
    public String wechatLogin(WechatLoginReq wechatLoginReq) {
        try {
            // 1. 验证微信授权码（这里简化处理，实际应该调用微信API验证）
            if (wechatLoginReq.getCode() == null || wechatLoginReq.getCode().isEmpty()) {
                throw new RuntimeException("微信授权码不能为空");
            }
            
            // 2. 根据微信用户信息查找或创建用户
            String openId = "wx_" + wechatLoginReq.getCode(); // 简化处理，实际应该通过code获取openId
            SysUser user = sysUserService.findByWechatOpenId(openId);
            
            if (user == null) {
                // 创建新用户
                user = new SysUser();
                user.setUsername(openId);
                user.setNickname(wechatLoginReq.getUserInfo().getNickName());
                user.setAvatar(wechatLoginReq.getUserInfo().getAvatarUrl());
                user.setGender(wechatLoginReq.getUserInfo().getGender());
                user.setWxOpenid(openId);
                user.setStatus(1); // 启用状态
                sysUserService.save(user);
            } else {
                // 更新用户信息
                user.setNickname(wechatLoginReq.getUserInfo().getNickName());
                user.setAvatar(wechatLoginReq.getUserInfo().getAvatarUrl());
                sysUserService.updateById(user);
            }
            
            // 3. 生成JWT token
            Map<String, Object> map = new HashMap<>();
            map.put("name", user.getUsername());
            map.put("loginType", "wechat");
            
            return JwtUtil.createJwt(jwtProperties.getUserSecretKey(), jwtProperties.getUserTtl(), String.valueOf(user.getId()), map);
            
        } catch (Exception e) {
            throw new RuntimeException("微信登录失败: " + e.getMessage());
        }
    }
}
